package com.zzzs.volatiledemo;

/**
 * 无法确保原子性
 * @author zhu_shuai
 * @since 2021/6/28
 */
public class Demo2 {

    private static volatile int num = 0; // 理论执行结果为 10000，但实际小于10000
    // private static AtomicInteger num = new AtomicInteger(0);

    public static void add() {
        num++;
        // num.getAndIncrement();
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(num);
    }

}
